package com.zl.learning.collection;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

public class TestBlockQueue {

    private static final BlockingQueue<String> queue = new LinkedBlockingDeque<>();
    private static volatile boolean start = true;
    private static final Object lock = new Object();
    private static final List<String> list = new ArrayList<>();

    public static void main(String[] args) {
        TestBlockQueue testBlockQueue = new TestBlockQueue();
        final Thread thread = new Thread(testBlockQueue::run);
        final Thread thread2 = new Thread(testBlockQueue::work);
        thread.start();
        thread2.start();
        Scanner scanner = new Scanner(System.in);
        String val = scanner.nextLine();
        while (!"exit".equals(val)) {
            String[] vv = val.split(",");
            queue.addAll(Arrays.asList(vv));
            val = scanner.nextLine();
        }
        thread.interrupt();
        thread2.interrupt();
    }

    private void run() {
        while (start) {
            try {
                String val = queue.take();
                synchronized (lock) {
                    list.add(val);
                    lock.notifyAll();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                start = false;
            }
        }
    }

    private void work() {
        synchronized (lock) {
            while (start) {
                while (!list.isEmpty()) {
                    list.forEach(r-> System.out.print(r+"---"));
                    System.out.println();
                    list.remove(0);
                    try {
                        lock.wait(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    start = false;
                }
            }

        }
    }
}
